package com.desksoft.ecommerce.util.html.element.query;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;

import com.desksoft.ecommerce.util.html.PageXml;
import com.desksoft.ecommerce.util.html.element.QueryElement;

/***************************************
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: 
 * 创建作者：luoy
 * 文件名称：存储过程查询元素
 * 版本：
 * 功能：
 * 最后修改时间：
 * 修改记录：
 *****************************************/
public class QueryProcedureElement extends QueryElement {

	protected String procedureName;						//	存储过程名
	protected List<QueryParam> paramL;					//	参数列表

	protected PageXml pageXml;
	
	public QueryProcedureElement() {
		super();
	}

	public QueryProcedureElement(Element element, PageXml pageXml){
		
		this.pageXml = pageXml;
		
		this.procedureName = element.element("procedure").attributeValue("name");
		this.paramL = parseParam(element.element("params"));
		this.queryFields = parseQueryField(element.element("columns"));
	}
	
	/**
	 * 解析查询字段
	 */
	protected QueryField[] parseQueryField(Element element){
		List<Element> columnElementL = element.elements("column");
		QueryField[] queryFieldA = new QueryField[columnElementL.size()];
		Element columnElement;
		QueryField field;
		for (int i=0;i<queryFieldA.length;i++){
			columnElement = columnElementL.get(i);
			field = new QueryField(columnElement.attributeValue("name"),columnElement.attributeValue("display"));
			queryFieldA[i] = field;
		}
		return queryFieldA;
	}
	
	/**
	 * 解析参数
	 * @return
	 */
	protected List<QueryParam> parseParam(Element element){
		
		List<Element> paramElementL = element.elements("param");
		List<QueryParam> res = new ArrayList<QueryParam>();
		QueryParam param;
		String indexStr,valueStr,classStr,defaultValue="";
		Class<?> type;
		for (Element paramElement : paramElementL) {
			indexStr = paramElement.attributeValue("index");
			valueStr = paramElement.attributeValue("value");
			valueStr = pageXml.getVarCollection().getValue(valueStr);
			classStr = paramElement.attributeValue("type");
			if (classStr == null){
				classStr = "java.lang.String";
			}
			defaultValue = paramElement.attributeValue("default");
			if (defaultValue == null){
				defaultValue = "";
			}
			defaultValue = this.pageXml.getVarCollection().replaceSql(defaultValue);
			
			try {
				type = Class.forName(classStr);
			} catch (ClassNotFoundException e) {
				type = String.class;
				e.printStackTrace();
			}
			param = new QueryParam(Integer.parseInt(indexStr),valueStr,defaultValue,type,classStr);
			res.add(param);
		}
		
		return res;
	}
	
	public String getProcedureName() {
		return procedureName;
	}
	public void setProcedureName(String procedureName) {
		this.procedureName = procedureName;
	}

	public List<QueryParam> getParamL() {
		return paramL;
	}

	public void setParamL(List<QueryParam> paramL) {
		this.paramL = paramL;
	}
	
}
